#!/bin/bash
set -xeuo pipefail
set -o errexit

if [ $# -eq 1 ]; then
 echo "ready to restore... $1"
else
 echo "should run: $0 backupname"
 exit 1
fi
:<<EOF
./delIndex.sh 
./restore.sh snapshot_20201204
#此时恢复的是总计6个文档的索引，每个索引3个
./delIndex.sh 
./restore.sh snapshot_20201205
#此时恢复的是12个文档的索引，每个索引6个
EOF

# 同一个集群内操练，为了成功恢复，需要删除索引
# ./delIndex.sh

curl -XGET "http://localhost:9200/_snapshot/backup/_all?pretty" | grep "$1" 
if [ $? -eq 0 ]; then
 echo "restore..."

 curl -XPOST "http://localhost:9200/_snapshot/backup/$1/_restore?pretty"
 :<<EOF
 如果存在同名索引的情况，出现如下错误
 {
  "error" : {
    "root_cause" : [
      {
        "type" : "snapshot_restore_exception",
        "reason" : "[backup:snapshot_20201205/gMt6IH0aR6uchnO3vztwHg] cannot restore index [test2] because an open index with same name already exists in the cluster. Either close or delete the existing index or restore the index under a different name by providing a rename pattern and replacement name"
      }
    ],
    "type" : "snapshot_restore_exception",
    "reason" : "[backup:snapshot_20201205/gMt6IH0aR6uchnO3vztwHg] cannot restore index [test2] because an open index with same name already exists in the cluster. Either close or delete the existing index or restore the index under a different name by providing a rename pattern and replacement name"
  },
  "status" : 500
}
EOF

 exit 0
else
 echo "backup not exist"
 exit 1
fi

